import {fetch} from '../../../utils/axios'
import router from '../../../router/index'

const state = {
  name: '项目列表',
  tempHeader: [],
  buildDialog: false,
  publishDialog: false,
  env: {},
  id: null,
  search: '',
  totalItems: 0,
  items: [],
  loading: true,
  pagination: {},
  headers: [],
  etext: 'No Data',
  rowsPerPageItems: [10, 50, 100, { text: 'All', value: 100000 }],
  searchLabel: 'name,name_en',
  snackbar: false,
  color: 'info',
  mode: '',
  timeout: 6000,
  text: 'Hello, I\'m a snackbar'
}

const mutations = {
  handlerPubProject: (state) => {
    state.loading = true
    const { sortBy, descending, page, rowsPerPage } = state.pagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/project_for_publish/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search,
      env: state.env.value
    }).then((response) => {
      state.items = response.results
      state.totalItems = response.count
      state.loading = false
    }).catch((error) => {
      state.etext = error.response
    })
  },
  loadPubProjectFilters (state) {
    fetch('/project/pubproject_filters/', {
    }).then((response) => {
      let res = JSON.parse(response)
      state.env.items = res.env
    }).catch((error) => {
      state.etext = error.response
    })
  },
  loadPubProjectHeaders (state) {
    fetch('/getmodels/', {
      appname: 'project',
      modelname: 'Project'
    }).then((response) => {
      state.headers = JSON.parse(response)
      state.tempHeader = JSON.parse(response)
      state.headers.splice(6, 0, {text: 'Actions', align: 'center', sortable: false})
    }).catch((error) => {
      state.etext = error.response
    })
  },
  openBuildList (state, payload) {
    // state.id = payload
    // state.buildDialog = true
    router.push({name: 'listbuild', params: payload})
  },
  openPublishList (state, payload) {
    // state.id = payload
    // state.publishDialog = true
    router.push({name: 'listPublish', params: payload})
  }
}

const actions = {
  handlerPubProject: ({commit}) => {
    commit('handlerPubProject')
  },
  pubProjectSearch ({commit, state}) {
    state.pagination.page = 1
    commit('handlerPubProject')
  },
  loadPubProjectFilters ({commit}) {
    commit('loadPubProjectFilters')
  },
  loadPubProjectHeaders ({commit}) {
    commit('loadPubProjectHeaders')
  },
  openBuildList ({commit}, payload) {
    commit('openBuildList', payload)
  },
  openPublishList ({commit}, payload) {
    commit('openPublishList', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
